package com.laihui.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;

import com.laihui.MyApplication;
import com.laihui.activity.BindCardActivity;
import com.laihui.activity.R;
import com.laihui.activity.InvestContentActivity;
import com.laihui.activity.LoginActivity;
import com.laihui.activity.RealnameActivity;

import com.laihui.adapters.LoanRecordAdapter;
import com.laihui.base.BaseFragment;
import com.laihui.entity.LoanList;
import com.laihui.entity.MemberBank;
import com.laihui.entity.RealBean;
import com.laihui.utils.ToastUtil;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.Unbinder;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 投资列表fragment
 */
@SuppressLint("ValidFragment")
public class BorrowListFragment extends BaseFragment {
    @BindView(R.id.easy_recycler_view)
    EasyRecyclerView easyRecyclerView;
    Unbinder unbinder;
    private Activity mActivity;
    private MyApplication application;
    private LoanRecordAdapter adapter;
    //当前页数
    private int pageNum = 1;
    //每一页显示的行数
    private int epage = 10;
    private String mParam1;
    private static final String ARG_PARAM1 = "param1";
    private static final String TAG = "BorrowListFragment";
    private  Integer type;
    @SuppressLint("ValidFragment")
    public BorrowListFragment(Integer type) {
        this.type =type;
    }
    public BorrowListFragment(){
    }
    private static boolean isRealName = false;//是否实名认证的标志
    private static boolean isBindBankCard = false;//是否绑定银行卡的标志

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("android.action.user.exit")) {

            } else if (intent.getAction().equals("android.action.toWithDraw")) {

            } else if (intent.getAction().equals("android.action.refresh")) {

                isBind();
                isReal();
                //getHotSale(true);
            }
        }
    };
    private void refresh() {

        isReal();
        isBind();
    }

    @Override
    public void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.action.user.exit");
        filter.addAction("android.action.toWithDraw");
        filter.addAction("android.action.refresh");
        mActivity.registerReceiver(receiver, filter);
        refresh();
    }

    //是否实名认证
    private void isReal() {
        Map<String, String> map = new HashMap<>();
        map.put("member_id", application.userId);
        application.apiService.toReal(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RealBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(RealBean toRealname) {

                        if (toRealname.item!=null) {
                            isRealName = true;
                        } else {
                            isRealName = false;
                        }
                    }
                });
    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {

            isReal();
            isBind();
        }
    }

    //是否绑定银行卡
    private void isBind() {
        Map<String, String> map = new HashMap<>();
        map.put("member_id", application.userId);
        Log.e(TAG, "isBind: "+application.userId );
        application.apiService.isBankBind(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<MemberBank>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(MemberBank memberBank) {
                       if(memberBank.item==null){
                           isBindBankCard =false;
                       }else{
                           isBindBankCard=true;
                       }
                    }
                });
    }


    public static BorrowListFragment newInstance(String param1, int type) {
        BorrowListFragment fragment = new BorrowListFragment(type);
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
        }
    }

    @Override
    public void init() {

        mActivity = getActivity();
        application = (MyApplication) mActivity.getApplication();
        easyRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter = new LoanRecordAdapter(mActivity);
        easyRecyclerView.setAdapter(adapter);
        getInvestRecord(false);
        easyRecyclerView.setErrorView(R.layout.error_layout);
        easyRecyclerView.setRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pageNum = 1;
                getInvestRecord(true);
            }
        });
        adapter.setMore(R.layout.load_none, new RecyclerArrayAdapter.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                pageNum++;
                getInvestRecord(false);
            }
        });
        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(final int position) {
                if (!application.isLogin) {
                    startActivity(new Intent(mActivity, LoginActivity.class));
                } else {
                    if (!isRealName) {
                        Log.e(TAG, "onViewClicked: " + isRealName);
                        startActivity(new Intent(mActivity, RealnameActivity.class));
                        ToastUtil.showToast(mActivity, "您未进行实名认证");
                    } else if (!isBindBankCard) {
                        Log.e(TAG, "onViewClicked: " + isBindBankCard);
                        startActivity(new Intent(mActivity, BindCardActivity.class));
                        ToastUtil.showToast(mActivity, "您未绑定银行卡");
                    } else {
                        Intent intent = new Intent(mActivity, InvestContentActivity.class);
                        intent.putExtra("loan", adapter.getItem(position));
                        startActivity(intent);
                    }

                }
            }
        });
    }

    private void getInvestRecord(final boolean isRefresh){
        Map<String,String > map = new HashMap<>();
        if(this.type!=null)
        map.put("loanCategory",this.type+"");
        map.put("currentPage",pageNum+"");
        application.apiService.loanlist(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<LoanList>() {
                    @Override public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError: "+e.toString() );
                    }


                    @Override
                    public void onNext(LoanList invest) {

                        if (isRefresh) {
                            adapter.clear();
                           /// adapter.addAll();
                        } else {

                            // adapter.addAll(invest.getBorrows());
                        }

                        adapter.addAll(invest.list);
                        adapter.notifyDataSetChanged();
                    }
                });

    }

    @Override
    public int getFragmentId() {
        return R.layout.fragment_borrow_record;
    }

    @Override
    public Object bindFragment() {
        return this;
    }



}
